package com.fancyy.scm.widget;

import android.content.Context;
import android.databinding.BindingAdapter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.widget.TextView;

import com.fancyy.scm.util.DensityUtil;

/**
 * Created by haungyin on 2015/4/28.
 */
public class CycleView extends AppCompatTextView {
    Paint paint;
    Paint mPaint = new Paint();
    int color1 = Color.parseColor("#FF0FDDA3");
    int color2 = Color.parseColor("#FF07B685");
    int cycleBgColor = Color.parseColor("#FFD8D8D8");

    public CycleView(Context context) {
        super(context);
        init(null);
    }

    public CycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public CycleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }


    private void init(AttributeSet attrs) {
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        mBorderWidth = DensityUtil.dip2px(getContext(), 5);
        mHalfBorder = mBorderWidth * 0.5f;
    }

    private float mBorderWidth;
    private float mHalfBorder;

    @Override
    protected void onDraw(Canvas canvas) {
        //刻度背景
        int center = (int) (getWidth() * 0.5f);
        int radius = (int) (center - mHalfBorder); //圆环的半径
        mPaint.setColor(cycleBgColor); //设置圆环的颜色
        mPaint.setStyle(Paint.Style.STROKE); //设置空心
        mPaint.setStrokeWidth(mBorderWidth); //设置圆环的宽度
        mPaint.setAntiAlias(true);  //消除锯齿
        canvas.drawCircle(center, center, radius, mPaint); //画出圆环
//        RectF oval = new RectF(center - radius, center - radius, center + radius, center + radius);
//        mPaint.setStyle(Paint.Style.STROKE);
//        canvas.drawArc(oval, 0, 360, false, mPaint);

        String text = getText().toString().replace("%", "");
        int percent = text.equals("") ? 0 : Integer.parseInt(text);
        // 进度
        if (percent > 0) {
            mPaint.setStrokeWidth(mBorderWidth);
            if (percent < 100) {
                setTextColor(color1);
                mPaint.setColor(color1);
            } else {
                setTextColor(color2);
                mPaint.setColor(color2);
            }
            RectF oval = new RectF(center - radius, center - radius, center + radius, center + radius);
            int angle = (int) (360 * percent / 100f);
            canvas.drawArc(oval, -90, angle, false, mPaint);
        } else {
            setTextColor(Color.parseColor("#FF333333"));
        }
        super.onDraw(canvas);
    }
}
